package com.romanito.timer;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Timer extends Activity {
		
	private final static String TAG = "com.romanito.timer";
	private final static int sNotifId = 1;
	
    private boolean mTimerRunning;
	private int mTimerSeconds;
	private long mStartTime;
	
	private AlarmManager mAlarmManager;
	private PendingIntent mPendingIntent;
	private Handler mHandler = new Handler();
	private SharedPreferences mPreferences;
	private NotificationManager mNotifManager;

	private NumberPicker np_minutes, np_seconds;
	private TextView tv_clock;
	private Button bt_StartStop;
	private LinearLayout ll_set_time;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    	mNotifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

		Intent intent = new Intent(this, TimerRing.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("NotifId", sNotifId);
		mPendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
		
        setVolumeControlStream(AudioManager.STREAM_ALARM);
        setContentView(R.layout.main);
        
        InitWidgets();
        
        /*
        AudioManager audio_manager = (AudioManager) getSystemService(AUDIO_SERVICE);
        int vol = audio_manager.getStreamVolume(AudioManager.STREAM_ALARM);
        bt_StartStop.setText(String.format("Volume: %d/%d", vol, audio_manager.getStreamMaxVolume(AudioManager.STREAM_ALARM)));
		*/

    }
    
	@Override
	protected void onStart() {
    	super.onStart();
		mTimerSeconds = mPreferences.getInt("timer_seconds", 0);
		mStartTime = mPreferences.getLong("start_time", 0L);
		mTimerRunning = (mStartTime != 0L);
		Log.d(TAG, String.format("onStart(timer_seconds=%d, start_time=%d)", mTimerSeconds, mStartTime));
        SetCountDownVisible(mTimerRunning);
	}

	/** Get references to UI widgets and initialize them if needed */
    private void InitWidgets() {
        tv_clock = (TextView) findViewById(R.id.tv_clock);
        
        ll_set_time = (LinearLayout) findViewById(R.id.ll_set_time);
        
        np_minutes = (NumberPicker) findViewById(R.id.np_minutes);
        np_minutes.setRange(0, 99);
        np_minutes.setSpeed(100);
        np_minutes.setCurrent(mPreferences.getInt("minutes", 0));
        
        np_seconds = (NumberPicker) findViewById(R.id.np_seconds);
        np_seconds.setRange(0, 59);
        np_seconds.setSpeed(100);
        np_seconds.setCurrent(mPreferences.getInt("seconds", 0));
        
        bt_StartStop = (Button) findViewById(R.id.bt_start_stop);
        bt_StartStop.setOnClickListener(bt_StartStop_OnClick);    	
    }

    private OnClickListener bt_StartStop_OnClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.d(TAG, String.format("bt_StartStop_OnClick(timer_running=%b)", mTimerRunning));
			if (mTimerRunning)
				SetTimerOn(false);
			else {				
				mTimerSeconds = np_minutes.getCurrent() * 60 + np_seconds.getCurrent();
				if (mTimerSeconds > 0)
					SetTimerOn(true);
			}
		}
	};
    
    private Runnable countdown_runnable = new Runnable() {
		@Override
		public void run() {
			Log.d(TAG, String.format("countdown_runnable.run(timer_running=%b)", mTimerRunning));
			long rem_secs = mTimerSeconds - (SystemClock.uptimeMillis() - mStartTime) / 1000;
			tv_clock.setText(FormatTime(Math.max(rem_secs, 0L)));
			if (rem_secs <= -1) 
				SetTimerOn(false);
			if (mTimerRunning)
				mHandler.postAtTime(this, mStartTime + (mTimerSeconds - rem_secs + 1) * 1000);
		}    	
    };
	
    /** Sets the timer on or off */
	private void SetTimerOn(boolean on) {
		Log.d(TAG, String.format("SetTimerOn(on=%b)", on));
		mTimerRunning = on;		
		SetAlarmOn(on);
		SetCountDownVisible(on);
		SetNotificationVisible(on);
	}
	
	/** Sets the alarm on or off
	 * 	This makes use of the alarm system service */
	private void SetAlarmOn(boolean on) {	
		Log.d(TAG, String.format("SetAlarmOn(on=%b)", on));
 		if (on) {
			mStartTime = SystemClock.uptimeMillis();
			mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + mTimerSeconds * 1000, mPendingIntent);
		}
		else {
			mStartTime = 0L;
			mAlarmManager.cancel(mPendingIntent);
		}
        SharedPreferences.Editor pref_edit = mPreferences.edit();
        pref_edit.putInt("timer_seconds", mTimerSeconds);
        pref_edit.putLong("start_time", mStartTime);
        pref_edit.commit();
	}
	
	/** Sets the countdown visible or not on screen.
	 * 	When off, the controls to set the timer values are shown instead. */
	private void SetCountDownVisible(boolean visible) {
		Log.d(TAG, String.format("SetCountDownVisible(visible=%b)", visible));
		if (visible) {
			mHandler.removeCallbacks(countdown_runnable);
			countdown_runnable.run();
		}
		else
			mHandler.removeCallbacks(countdown_runnable);
		bt_StartStop.setText(visible ? R.string.cancel : R.string.start);
		tv_clock.setVisibility(visible ? View.VISIBLE : View.GONE);
		ll_set_time.setVisibility(visible ? View.GONE : View.VISIBLE);
	}
	
    private void SetNotificationVisible(boolean visible) {    	
		Log.d(TAG, String.format("SetNotificationVisible(visible=%b)", visible));
		if (visible){
            CharSequence text = getResources().getText(R.string.notif_timer_running);
            CharSequence title = getResources().getText(R.string.app_name);

            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, Timer.class), 0);

            Notification notification = new Notification(R.drawable.stat_notify_alarm, text, System.currentTimeMillis());
            notification.setLatestEventInfo(this, title, text, contentIntent);
            notification.flags |= Notification.FLAG_ONGOING_EVENT;

        	mNotifManager.notify(sNotifId, notification);
    	}
    	else
        	mNotifManager.cancel(sNotifId);
    }
    
	private String FormatTime(long l) {
		return String.format("%d:%02d", l / 60, l % 60);	
	}

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		startActivity(new Intent(this, SettingsActivity.class));
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStop() {
		super.onStop();
		
        SharedPreferences.Editor pref_edit = mPreferences.edit();
        pref_edit.putInt("minutes", np_minutes.getCurrent());
        pref_edit.putInt("seconds", np_seconds.getCurrent());
        pref_edit.commit();

	}

}